import {useMutation, useQuery, useQueryClient} from '@tanstack/react-query';
import {cancelOrder, createOrder, getUserOrders, payOrder} from '../api/divide/order/sdk.gen';
import type {CancelOrderRequest, CreateOrderRequest, PayOrderRequest} from '../api/divide/order/types.gen';
import {message} from 'antd';

export const useOrders = () => {
    const queryClient = useQueryClient();

    // 获取用户订单列表
    const {
        data: orders,
        isLoading: isLoadingOrders,
        error: ordersError,
        refetch: refetchOrders
    } = useQuery({
        queryKey: ['orders'],
        queryFn: () => getUserOrders().then(res => res.data?.data || []),
        staleTime: 1000 * 60 * 5, // 5分钟缓存
    });

    // 创建订单
    const createOrderMutation = useMutation({
        mutationFn: (params: CreateOrderRequest) => createOrder({body: params}),
        onSuccess: (data) => {
            message.success('订单创建成功');
            queryClient.invalidateQueries({queryKey: ['orders']});
            return data.data;
        },
        onError: (error) => {
            message.error('创建订单失败：' + (error as Error).message);
        }
    });

    // 支付订单
    const payOrderMutation = useMutation({
        mutationFn: (params: PayOrderRequest) => payOrder({body: params}),
        onSuccess: () => {
            message.success('支付成功');
            queryClient.invalidateQueries({queryKey: ['orders']});
        },
        onError: (error) => {
            message.error('支付失败：' + (error as Error).message);
        }
    });

    // 取消订单
    const cancelOrderMutation = useMutation({
        mutationFn: (params: CancelOrderRequest) => cancelOrder({body: params}),
        onSuccess: () => {
            message.success('订单取消成功');
            queryClient.invalidateQueries({queryKey: ['orders']});
        },
        onError: (error) => {
            message.error('取消订单失败：' + (error as Error).message);
        }
    });

    return {
        // 数据
        orders: orders || [],
        isLoadingOrders,
        ordersError,

        // 操作函数
        createOrder: createOrderMutation.mutate,
        payOrder: payOrderMutation.mutate,
        cancelOrder: cancelOrderMutation.mutate,
        refetchOrders,

        // 状态
        isCreating: createOrderMutation.isPending,
        isPaying: payOrderMutation.isPending,
        isCancelling: cancelOrderMutation.isPending
    };
};